<template>
  <el-select
    v-model="state"
    v-bind="$attrs"
    clearable
    style="width: 100%;"
    v-on="$listeners"
  >
    <el-option
      v-for="item in getOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
      <slot v-bind="item || {}" />
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: 'VSelect',
  inheritAttrs: false,
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: null,
    options: Array,
    numberToString: Boolean,
    labelField: {
      type: String,
      default: 'label'
    },
    valueField: {
      type: String,
      default: 'value'
    }
  },
  data() {
    return {
      state: this.value
    }
  },
  watch: {
    value(val) {
      this.state = val
    },
    state(val) {
      this.$emit('input', val)
    }
  },
  computed: {
    getOptions() {
      const {
        labelField,
        valueField,
        numberToString,
        options: defaultOptions
      } = this

      return (defaultOptions || []).reduce((prev, next) => {
        if (next) {
          const value = next[valueField]
          prev.push({
            ...next,
            label: next[labelField],
            value: numberToString ? `${value}` : value
          })
        }
        return prev
      }, [])
    }
  }
}
</script>
